import { getCurrentUserInfoApi } from '@/services';
import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'


const userInfo: any = {}

const initialUserState = {
  userInfo,
}

/**
 * 异步处理
 * 获取用户信息
 */
export const getUserInfoAsync = createAsyncThunk(
  'user/getCurrentUserInfo',
  async () => {
    let res = await getCurrentUserInfoApi();
    return res.data;
  }
);

export const userSlice = createSlice({
  name: 'user',
  initialState: initialUserState,
  reducers: {
    updateUserInfo: (state, actions: PayloadAction<any>) => {
      state.userInfo = actions.payload
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(getUserInfoAsync.fulfilled, (state, action) => {
        state.userInfo = action.payload;
      })
      .addCase(getUserInfoAsync.rejected, (state) => {
        state.userInfo = {};
      })
  },
})

export const userActions = userSlice.actions

export const userReducer = userSlice.reducer

export const UserType = typeof initialUserState

